package com.ciaojian.timer.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.config.FuluOpenConfig;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.mapper.DFulugoodsMapper;
import com.ciaojian.core.mapper.OrderMapper;
import com.ciaojian.core.mapper.PhoneCreditMapper;
import com.ciaojian.core.model.CouponCode;
import com.ciaojian.core.model.DFulugoods;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.PhoneCredit;
import com.ciaojian.core.model.fulu.*;
import com.ciaojian.core.util.FuluUtil;
import com.ciaojian.core.util.JsonUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class FuluTask {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private PhoneCreditMapper phoneCreditMapper;
    @Resource
    private CouponCodeMapper couponCodeMapper;
    @Resource
    private DFulugoodsMapper dFulugoodsMapper;

    //福禄手机号定时充值
    @Scheduled(cron = "0 15 * * * ?")   //  xx:15:00=
    public void autoFuluStatus() {
        try {
            log.info("##autoFuluStatus##");
            QueryWrapper<PhoneCredit> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.eq("status", 0);
            objectQueryWrapper.lt("requests_num", 6);

            List<PhoneCredit> bPhoneCredits = phoneCreditMapper.selectList(objectQueryWrapper);

            for (PhoneCredit phoneCredit : bPhoneCredits) {
                try {

                    Order order = orderMapper.selectById(phoneCredit.getOrderId());
                    String orderJson = "";
                    if (phoneCredit.getRequestsNum()==1){
                        orderJson = "{\"customer_order_no\": \"" + order.getOrderNo() + "\"}";
                    }else {
                        orderJson = "{\"customer_order_no\": \"" + order.getOrderNo() + phoneCredit.getRequestsNum() + "\"}";
                    }

                    phoneCredit.setRequestsNum(phoneCredit.getRequestsNum() + 1);
                    phoneCreditMapper.updateById(phoneCredit);
                    log.info("##autoFuluStatus##2");

                    FuluRequest fuluOrderRequest = FuluUtil.newFuluRequest(orderJson, FuluOpenConfig.ORDERINFO_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                    String fuluOrderRequestJson = JsonUtil.toJson(fuluOrderRequest);
                    String fuluOrderResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluOrderRequestJson);

                    FuluResponse fuluOrderResponse = JsonUtil.fromJson(fuluOrderResponseJson, FuluResponse.class);

                    if (fuluOrderResponse.getCode() != 0) {
                        phoneCreditMapper.updateById(phoneCredit);
                        continue;
                    }

                    OrderInfo orderInfo = JsonUtil.fromJson(fuluOrderResponse.getResult(), OrderInfo.class);

                    if (phoneCredit.getStatus() != 1) {
                        if ("success".equals(orderInfo.getOrder_state())) {
                            phoneCredit.setTradeNo(orderInfo.getOrder_id());
                            phoneCredit.setStatus(1);
                            QueryWrapper<CouponCode> couponCodeQueryWrapper = new QueryWrapper<>();
                            couponCodeQueryWrapper.eq("outside_code", phoneCredit.getCode());
                            CouponCode couponCode = couponCodeMapper.selectOne(couponCodeQueryWrapper);
                            couponCode.setStatus(2);
                            phoneCreditMapper.updateById(phoneCredit);
                            couponCodeMapper.updateById(couponCode);
                            continue;
                        }
                        if ("processing".equals(orderInfo.getOrder_state()) || "untreated".equals(orderInfo.getOrder_state())) {
                            phoneCredit.setTradeNo(orderInfo.getOrder_id());
                            phoneCredit.setStatus(2);  //受理中
                            phoneCreditMapper.updateById(phoneCredit);
                            continue;
                        }
                        if ("failed".equals(orderInfo.getOrder_state())) {
                            phoneCredit.setTradeNo(orderInfo.getOrder_id());
                            phoneCredit.setStatus(0);  //失败
                            phoneCreditMapper.updateById(phoneCredit);
                        }
                    }

                    if (phoneCredit.getStatus() == 0) {
                        QueryWrapper<CouponCode> codeQueryWrapper = new QueryWrapper<>();
                        codeQueryWrapper.eq("outside_code", phoneCredit.getCode());
                        CouponCode couponCode = couponCodeMapper.selectOne(codeQueryWrapper);

                        //基础参数
                        DirectAdd directAdd = new DirectAdd();
                        //三网话费
                        QueryWrapper<DFulugoods> fuluqw = new QueryWrapper<>();
                        fuluqw.eq("coupon_id", couponCode.getCouponId());
                        DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fuluqw);

                        Assert.isTrue(ObjectUtil.isNotEmpty(dFulugoods), "暂时无法充值,请稍后01");

                        if (dFulugoods.getStatus() != 0 && dFulugoods.getFuluStatus() != 0 && dFulugoods.getStockStatus() != 0) {
                            Assert.notNull(null, "暂时无法充值,请稍后02");
                        }


                        directAdd.setProduct_id(dFulugoods.getFuluGoodsId());

                        directAdd.setCustomer_order_no(order.getOrderNo() + phoneCredit.getRequestsNum());
                        directAdd.setCharge_account(phoneCredit.getUserPhone());
                        directAdd.setBuy_num(1);
                        directAdd.setContact_tel(phoneCredit.getUserPhone());
                        directAdd.setExternal_biz_id(order.getId().toString());
                        String directAddJson = JsonUtil.toJson(directAdd);

                        //封装请求参数 请求fulu (正式)
                        FuluRequest fuluRequest = FuluUtil.newFuluRequest(directAddJson, FuluOpenConfig.DIRECT_ADD_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
                        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);


//                     (测试沙箱)
//                    FuluRequest fuluRequest = FuluUtil.newFuluRequest(directAddJson,FuluOpenConfig.DIRECT_ADD_METHOD,FuluOpenConfig.APP_KEY_TEST,FuluOpenConfig.SYSSECRET_TEST);
//                    String fuluRequestJson = JsonUtil.toJson(fuluRequest);
//                    String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_TEST_URL, fuluRequestJson);
//
                        FuluResponse fuluResponse = JsonUtil.fromJson(fuluResponseJson, FuluResponse.class);

                        //充值请求成功
                        if (fuluResponse.getCode() == 0) {
                            String result = fuluResponse.getResult();
                            DirectAddResponse directAddResponse = JsonUtil.fromJson(result, DirectAddResponse.class);

                            String orderJson1 = "{\"customer_order_no\": \"" + directAdd.getCustomer_order_no() + "\"}";
                            FuluRequest orderJsonRequest = FuluUtil.newFuluRequest(orderJson1, FuluOpenConfig.ORDERINFO_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
                            String orderfulu = JsonUtil.toJson(orderJsonRequest);
                            String post = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, orderfulu);
                            FuluResponse fuluResponse1 = JsonUtil.fromJson(post, FuluResponse.class);

                            OrderInfo orderInfo1 = JsonUtil.fromJson(fuluResponse1.getResult(), OrderInfo.class);

                            phoneCredit.setTradeNo(directAddResponse.getOrder_id());
                            if (orderInfo1.getOrder_state().equals("success")) {
                                phoneCredit.setTradeNo(orderInfo1.getOrder_id());
                                phoneCredit.setStatus(1);
                            }
                            if (orderInfo1.getOrder_state().equals("processing") || orderInfo.getOrder_state().equals("untreated")) {
                                phoneCredit.setTradeNo(orderInfo1.getOrder_id());
                                phoneCredit.setStatus(2);
                            }
                            if (orderInfo1.getOrder_state().equals("failed")) {
                                phoneCredit.setTradeNo(orderInfo1.getOrder_id());
                                phoneCredit.setStatus(0);
                            }
                        }
                        phoneCreditMapper.updateById(phoneCredit);

                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    //福禄商品定时更新  10分钟一次
    @Scheduled(cron = "0 0/10 * * * ?")
    public void autoFuluGoodsStatus() {
        String d = "{\"first_category_id\": \"\",}";
        FuluRequest fuluRequest = FuluUtil.newFuluRequest(d, FuluOpenConfig.GOODSLIST_GET_METHOD, FuluOpenConfig.APP_KEY, FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        FuluGoods fuluGoods = JsonUtil.fromJson(fuluResponseJson, FuluGoods.class);

        String result = fuluGoods.getResult();
        Gson gson = new GsonBuilder().create();
        List<FuluGoodsList> fuluGoodsLists = gson.fromJson(result, new TypeToken<List<FuluGoodsList>>() {
        }.getType());

        for (FuluGoodsList fuluGoodsList : fuluGoodsLists) {
            QueryWrapper<DFulugoods> fgqw = new QueryWrapper<>();
            fgqw.eq("fulu_goods_id", fuluGoodsList.getProduct_id());
            DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fgqw);

            if (ObjectUtil.isNotNull(dFulugoods)) {
                dFulugoods.setGoodsTitle(fuluGoodsList.getProduct_name());
                dFulugoods.setGoodsType(fuluGoodsList.getProduct_type());
                dFulugoods.setFaceValue(fuluGoodsList.getFace_value());
                dFulugoods.setPurchasePrice(fuluGoodsList.getPurchase_price());
                dFulugoods.setUpdateTime(new Date());

                switch (fuluGoodsList.getStock_status()) {
                    case "充足":
                        dFulugoods.setStockStatus(0);
                        break;
                    case "断货":
                        dFulugoods.setStockStatus(1);
                        break;
                    case "警报":
                        dFulugoods.setStockStatus(2);
                        break;
                    default:
                        break;
                }

                switch (fuluGoodsList.getSales_status()) {
                    case "上架":
                        dFulugoods.setFuluStatus(0);
                        break;
                    case "下架":
                        dFulugoods.setFuluStatus(1);
                        break;
                    case "维护中":
                        dFulugoods.setFuluStatus(2);
                        break;
                    case "库存维护":
                        dFulugoods.setFuluStatus(3);
                        break;
                    default:
                        break;
                }
                dFulugoodsMapper.updateById(dFulugoods);
            }
        }
    }
}
